package main

import (
	"fmt"
	"time"
)

/**
 * @description 
 * @time 2018/5/12 19:18
 * @version 
 */
func main() {
	//fmt.Println("Channel as first-class citizen")
	//channelDemo()
	//fmt.Println("Buffered channel")
	//bufferedChannel()
	//fmt.Println("Channel close and range")
	//channelClose()
	chanDemo1()
}

func channelDemo() {
	var channels [10] chan<- int
	for i := 0; i < 10; i++ {
		channels[i] = createWorker(i)
	}

	for i := 0; i < 10; i++ {
		channels[i] <- 'a' + i
		//fmt.Println("111111")
		//m:=<- channels[i] 错误方式
	}

	for i := 0; i < 10; i++ {
		channels[i] <- 'A' + i
	}

	time.Sleep(time.Microsecond)
}

//提供给外部一个可以往里面发数据的channel,里面的channel就负责收数据
func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id, c)
	return c
}

func worker(id int, c chan int) {
	for {
		n, ok := <-c
		if !ok {
			break
		}
		fmt.Printf("Worker %d received %c\n", id, n)
	}
	//for n:= range c{
	//	fmt.Printf("Worker %d received %c\n", id, n)
	//}
}

func chanDemo1() {
	c := make(chan int)

	go foo(c)
	//go func() {
	//	for {
	//		<-c
	//		//i := <-c
	//		//fmt.Println(i)
	//	}
	//}()
	//向channel发送一个数据1
	<-c
}

func foo(ch chan int) {
	ch <- 0
}



func channelClose() {
	c := make(chan int)
	go worker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	c <- 'd'
	close(c)
	time.Sleep(time.Microsecond)
}

func bufferedChannel() {
	//一般来说，chanel发数据后，必须有channel来收，如果没有，系统就会报deadlock错误
	//缓冲区可以容纳3size,不用切换协程
	//c := make(chan int, 3)
	//go worker(0, c)
	//c <- 'a'
	//c <- 'b'
	//c <- 'c'
	//c <- 'd'
	c := make(chan int)
	go func() {
		i := <-c
		fmt.Println(i)
	}()
	c <- 1
	time.Sleep(time.Microsecond)
}
